import { debounce } from 'lodash'

const DebouncePlugin = {
  install(Vue, options = {}) {
    // 配置默认参数
    const defaultDelay = options.defaultDelay || 500
    const defaultOptions = {
      leading: false,
      trailing: true,
      ...options.defaultOptions
    }

    // 添加实例方法
    Vue.mixin({
      created() {
        this.$createDebounce = function(fn, delay, options) {
          const debouncedFn = debounce(fn, delay || defaultDelay, { ...defaultOptions, ...options })

          // 自动注册销毁钩子
          const originalDestroy = this.$options.beforeDestroy || []
          this.$options.beforeDestroy = [].concat(originalDestroy, () => {
            debouncedFn.cancel()
          })

          return debouncedFn
        }
      }
    })
  }
}

export default DebouncePlugin
